package com.sunlong.jiangwei.util;

import com.sunlong.jiangwei.util.entity.MinioLink;
import io.minio.*;
import io.minio.errors.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Map;

@Component
public class MinioUtils {

    @Autowired
    private MinioLink minioLink;

    /**
     * 根据路径删除对应文件
     * @param minioPath
     */
    public void deleteMinioFile(String bucketName, String minioPath) throws Exception{
        MinioClient minioClient = getMinioClient();
        minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(minioPath).build());

    }

    public MinioClient getMinioClient(){
        MinioClient minioClient = MinioClient.builder().endpoint(minioLink.getUrl()).credentials(minioLink.getUsername(), minioLink.getPassword()).build();
        return minioClient;
    }

    public String upload(String bucketName,int mode, InputStream inputStream, String key) throws Exception{
        MinioClient minioClient = getMinioClient();
        String contentType = "";
        //0表示png，1表示jpg
        switch (mode){
            case 0:
                contentType = "application/x-png";
                key = key + ".png";
                break;
            default:
                contentType = "image/jpeg";
                key = key + ".jpg";
                break;
        }
        try {
            uploagFile(minioClient,bucketName, key, contentType,inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String objectUrl = minioClient.getObjectUrl(bucketName, key);
        return objectUrl;
    }

    private void uploagFile(MinioClient minioClient, String bucketName, String key, String contentType, InputStream inputStream) throws ErrorResponseException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException, IOException, NoSuchAlgorithmException, ServerException, XmlParserException {
        minioClient.putObject(PutObjectArgs.builder()
                .contentType(contentType)
                .bucket(bucketName)
                .object(key)
                .stream(inputStream, inputStream.available(), -1).build());
    }

    /**
     * 根据参数file获取inputstream流
     * @param context
     * @return
     */
    @NotNull
    public static ByteArrayInputStream getStream(Map<String, Object> context) {
        String file = (String) context.get("file");
        String s = file.split(",")[1];
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(s);
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        return stream;
    }
}
